package cn.coisini.service.impl;

import cn.coisini.mapper.ArticleMapper;
import cn.coisini.mapper.CategoryMapper;
import cn.coisini.model.common.dtos.Result;
import cn.coisini.model.common.enums.ResultEnum;
import cn.coisini.model.dto.CategoryDto;
import cn.coisini.model.pojo.Article;
import cn.coisini.model.pojo.Category;
import cn.coisini.model.pojo.User;
import cn.coisini.model.vo.QueryVo;
import cn.coisini.service.CategoryService;
import cn.coisini.service.UserService;
import cn.coisini.utils.IdWorker;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.coisini.model.common.constants.AdminConstants.*;
import static cn.coisini.utils.JwtUtil.getUserIdFromToken;

/**
 * @author xiangshaw
 * Description: 类别接口实现类
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    private final UserService userService;
    private final ArticleMapper articleMapper;

    // 根据名称查询
    @Override
    public Category findByName(String categoryName) {
        String userIdFromToken = getUserIdFromToken();
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<Category>()
                .eq(CATEGORY_NAME, categoryName)
                .eq(CREATE_USER, userIdFromToken);
        Category category = baseMapper.selectOne(categoryQueryWrapper);
        return category;
    }

    // 根据id查询分类名称
    @Override
    public Category findById(String id) {
        return baseMapper.selectById(id);
    }

    // 根据ids查询分类名称
    @Override
    public List<Category> findByIds(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return Collections.emptyList();
        }
        QueryWrapper<Category> categoryIds = new QueryWrapper<Category>().in("id", ids);
        return baseMapper.selectList(categoryIds);
    }

    // 新增分类
    @Override
    public Result<ResultEnum> addCategory(CategoryDto categoryDto) {
        // 1.根据token获取用户id
        String userId = getUserIdFromToken();
        if (userId == null) {
            return Result.error(ResultEnum.DATA_NOT_FOUND_BY_USERNAME);
        }
        // 2.检查分类是否已存在
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(CATEGORY_NAME, categoryDto.getCategoryName()).eq(CREATE_USER, userId);
        Category existingCategory = this.getOne(queryWrapper);
        if (existingCategory != null) {
            return Result.error(ResultEnum.DATA_EXIST, "该分类已存在");
        }
        // 3.封装数据
        Category category = new Category();
        category.setId(String.valueOf(new IdWorker().nextId()));
        category.setCategoryName(categoryDto.getCategoryName());
        category.setCategoryAlias(categoryDto.getCategoryAlias());
        category.setRecommend(categoryDto.getRecommend());
        category.setStatus(categoryDto.getStatus());
        category.setCreateUser(userId);
        LocalDateTime currentTime = LocalDateTime.now();
        category.setCreateTime(currentTime);
        category.setUpdateTime(currentTime);
        // 4.新增分类
        boolean savedCategory = this.save(category);
        if (savedCategory) {
            return Result.ok(ResultEnum.SUCCESS);
        }
        return Result.error(ResultEnum.DATA_UPDATE_FAILED);
    }


    //  查询分类列表
    @Override
    public Result<Object> getCategoryList(QueryVo queryVo) {
        // 获取用户信息
        String userId = getUserIdFromToken();
        // 1.获取查询条件
        String categoryName = queryVo.getKeyword();
        // 2.封装查询条件
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        if (categoryName != null && !categoryName.isEmpty()) {
            queryWrapper.like(CATEGORY_NAME, categoryName)
                    .eq(CREATE_USER, userId);
        }
        queryWrapper.eq(CREATE_USER, userId);
        queryWrapper.orderByDesc("create_time");
        // 3.分页条件，当前页、每页条数
        Page<Category> page = new Page<>(queryVo.getCurrent(), queryVo.getLimit());
        Page<Category> categoryPage = page(page, queryWrapper);
        // 4.获取分类列表
        List<Category> categories = categoryPage.getRecords();
        // 5.获取所有分类的创建用户ID
        List<String> userIds = categories.stream().map(Category::getCreateUser).toList();
        // 6.获取所有分类的用户信息
        Map<String, User> userMap = userService.getUserMapByIds(userIds);
        // 7.遍历分类列表，设置创建用户名称
        categories.forEach(category -> {
            User user = userMap.get(category.getCreateUser());
            if (user != null) {
                category.setCreateUser(user.getUsername());
            }
        });
        // 8.封装返回结果
        Result<Object> result = new Result<>();
        result.setData(categoryPage);
        return result;
    }

    /**
     * 获取文章分类列表
     */
    @Override
    public Result<List<Category>> getArticleCategoryList() {
        String userId = getUserIdFromToken();
        // 使用 LambdaQueryWrapper 构建查询条件
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getCreateUser, userId);
        // 查询数据库并返回结果
        return Result.ok(baseMapper.selectList(queryWrapper));
    }

    // 修改分类
    @Override
    public Result<ResultEnum> updateCategory(CategoryDto categoryDto) {
        // 1.修改分类
        Category category = new Category();
        BeanUtils.copyProperties(categoryDto, category);
        category.setUpdateTime(LocalDateTime.now());
        // 2.执行更新操作
        boolean updateCategoryById = this.updateById(category);
        if (updateCategoryById) {
            return Result.ok(ResultEnum.SUCCESS);
        }
        return Result.error(ResultEnum.DATA_UPDATE_FAILED);
    }

    // 删除分类
    @Override
    public Result<ResultEnum> deleteCategory(String id) {
        // 检查是否有文章与该分类相关联
        if (hasArticlesWithCategory(id)) {
            return Result.error(ResultEnum.DATA_DELETE_FAILED, "该分类下存在文章，无法删除");
        }
        // 删除分类
        int i = baseMapper.deleteById(id);
        return i > FALSE ? Result.ok(ResultEnum.SUCCESS) : Result.error(ResultEnum.DATA_DELETE_FAILED);
    }

    // 检查是否有文章与指定分类相关联
    private boolean hasArticlesWithCategory(String categoryId) {
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<Article>().eq("category_id", categoryId);
        long count = articleMapper.selectCount(articleQueryWrapper);
        return count > FALSE;
    }

    // 批量删除分类
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<ResultEnum> deleteCategoryByIds(List<String> ids) {
        // 检查是否有文章关联这些分类
        List<Article> associatedArticles = articleMapper.selectList(new QueryWrapper<Article>().in("category_id", ids));
        if (!associatedArticles.isEmpty()) {
            return Result.error(ResultEnum.DATA_DELETE_FAILED, "部分分类下存在文章，无法删除");
        }
        // 批量删除分类
        int i = baseMapper.deleteBatchIds(ids);
        return i > FALSE ? Result.ok(ResultEnum.SUCCESS) : Result.error(ResultEnum.DATA_DELETE_FAILED);
    }

    @Override
    public Map<String, String> getCategoryNamesByIds(List<String> categoryIds) {
        // 批量查询分类信息
        List<Category> categories = baseMapper.selectBatchIds(categoryIds);
        return categories.stream()
                .collect(Collectors.toMap(Category::getId, Category::getCategoryName));
    }

    // 获取用户分类
    @Override
    public List<Map<String, Object>> getCategoryByUserId(String userId) {
        return getMapList(userId, FALSE);
    }

    // 获取推荐分类
    @Override
    public List<Map<String, Object>> getRcategoryByUserId(String userId) {
        return getMapList(userId, TRUE);
    }

    // 获取分类列表（公共方法）
    private List<Map<String, Object>> getMapList(String userId, short recommend) {
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        categoryQueryWrapper
                .eq("create_user", userId)
                .eq("recommend", recommend)
                .select("id", "category_name", "recommend", "status");
        // 获取查询结果
        List<Map<String, Object>> categories = baseMapper.selectMaps(categoryQueryWrapper);

        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper
                .eq("status", FALSE)
                .select("id", "category_name", "recommend", "status");
        categories.addAll(baseMapper.selectMaps(wrapper));
        // 去重
        categories = categories.stream().distinct().collect(Collectors.toList());
        // 将id转换为String类型
        for (Map<String, Object> category : categories) {
            Object id = category.get("id");
            if (id != null) {
                category.put("id", id.toString());
            }
        }
        // 返回分类ID和分类名称
        return categories;
    }

    // 添加或取消推荐分类
    @Override
    public Result<ResultEnum> updateRecommendCategory(CategoryDto categoryDto) {
        // 验证输入数据
        if (categoryDto == null || categoryDto.getId() == null || categoryDto.getRecommend() == null) {
            return Result.error(ResultEnum.PARAM_ERROR);
        }
        // 更新推荐状态
        UpdateWrapper<Category> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", categoryDto.getId())
                .set("recommend", categoryDto.getRecommend())
                .set("update_time", LocalDateTime.now());

        int rows = baseMapper.update(null, updateWrapper);
        if (rows > 0) {
            return Result.ok(ResultEnum.SUCCESS);
        } else {
            return Result.error(ResultEnum.DATA_UPDATE_FAILED);
        }
    }
}
